package com.winit.openapi.interceptor.validator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.oauth.vo.APIClientVo;
import com.winit.openapi.util.APISysConfigUtil;
import com.winit.openapi.util.RequestUtil;

public abstract class OAuth2APIRequestValidator<T extends HttpServletRequest> extends AbstractAPIRequestHandler<T> {

    @Resource
    private APISysConfigUtil         apiSysConfigUtil;

    public void checkClient(HttpServletRequest request) throws ApiException {
        RequestMsg requestMsg = RequestUtil.getRequestMsg(request);
        if (StringUtils.isBlank(requestMsg.getClient_id())) {
            return;
        }
        APIClientVo clientVo = apiSysConfigUtil.getClientByKey(requestMsg.getClient_id());
        if (clientVo == null) {
            throw new ApiException(ErrorCode.OAUTH_CLIENT_NOT_EXISTS_ERROR, requestMsg.getClient_id());
        }
        String platform = requestMsg.getPlatform();
        if (!clientVo.getClientCode().equals(platform)) {
            throw new ApiException(ErrorCode.OAUTH_PLATFORM_NOT_MATCH_ERROR, platform);
        }
        CommandContext ctx = CommandContext.getContext();
        // oauth2应用信息
        ctx.set(ApiConstant.API_CLIENT, clientVo);

    }

    public void checkClientSign(HttpServletRequest request) throws ApiException {
        RequestMsg requestMsg = RequestUtil.getRequestMsg(request);
        if (requestMsg == null) {
            return;
        }
        String sign = requestMsg.getClient_sign();
        CommandContext ctx = CommandContext.getContext();
        // oauth2应用信息
        APIClientVo client = ctx.get(ApiConstant.API_CLIENT);
        checkSign(request, client.getClientSecret(), sign);
    }

    public void checkAccessToken(T request) throws ApiException {

    }

    public void checkRole(T request) throws ApiException {

    }

}
